package gqz.avdemo.pusher;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

import java.net.Socket;

import gqz.avdemo.R;

public class PusherAct extends AppCompatActivity {

   MediaProjectionManager projectionManager;
   SocketLive live;
   private EditText et;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      et = findViewById(R.id.main_port);
      checkPermission();
      findViewById(R.id.main_start).setOnClickListener(v -> {
         projectionManager = (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
         Intent intent = projectionManager.createScreenCaptureIntent();
         startActivityForResult(intent, 1);
      });
   }

   @Override
   protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
      super.onActivityResult(requestCode, resultCode, data);
      if (resultCode == RESULT_OK && requestCode == 1) {
         MediaProjection projection = projectionManager.getMediaProjection(resultCode, data);
         if (projection != null) {
            live = new SocketLive(projection, Integer.parseInt(et.getText().toString()));
         }
      }
   }

   public void checkPermission() {
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(
              Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
         requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                 Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
      }
   }

   @Override
   protected void onDestroy() {
      super.onDestroy();
      live.onDestroy();
   }
}